﻿using System.Web.Helpers;
using IrisMembership.DataLayer;
using IrisMembership.DomainClasses;
using IrisMembership.ServiceLayer;
using IrisMembership.Web.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using IrisMembership.Web.Authentication;

namespace IrisMembership.Web.Controllers
{
    public class AccountController : Controller
    {
        private readonly IIrisDbContext _dbContext;
        private readonly IUserService _userService;
        private readonly IRoleService _roleService;
        private readonly IFormsAuthenticationService _formAuthentication;

        public AccountController(IIrisDbContext dbContext, IUserService userService, IRoleService roleService, IFormsAuthenticationService formsAuthentication)
        {
            _dbContext = dbContext;
            _userService = userService;
            _roleService = roleService;
            _formAuthentication = formsAuthentication;
        }

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult Login()
        {
            return PartialView();
        }

        [HttpPost]
        public async Task<ActionResult> Login(LoginModel loginModel)
        {
            var user = await _userService.FindByEmailAsync(loginModel.Identity);

            if (user == null)
                return Json("noooo");

            if (Crypto.VerifyHashedPassword(user.Password, loginModel.Password))
            {
                _formAuthentication.SignIn(new UserTicket
                {
                    Name = user.Name,
                    UserId = user.Id,
                    UserName = user.UserName
                }, loginModel.RememberMe);
            }
            else
            {
                return Json("no");
            }

            return Json("ok");
        }

        public ActionResult Register()
        {
            return PartialView();
        }

        [HttpPost]
        public async Task<ActionResult> Register(RegisterModel registerModel)
        {
            var userRole = new Role { Id = 2 };
            _roleService.AttachToContext(userRole);

            await _userService.AddAsync(new User
           {
               UserName = registerModel.UserName,
               Email = registerModel.Email,
               Name = registerModel.Name,
               Password = Crypto.HashPassword(registerModel.Password),
               Roles = new List<Role> { userRole }
           });

            await _dbContext.SaveChangesAsync();

            return Json("ok");
        }

        public ActionResult SignOut()
        {
            _formAuthentication.SignOut();

            return View();
        }

    }
}